#define _CRT_SECURE_NO_WARNINGS 1

class Solution {
public:
    ListNode* reverse(ListNode* head)
    {
        ListNode* pre = nullptr;
        ListNode* cur = head;
        while (cur != nullptr)
        {
            ListNode* Next = cur->next;
            cur->next = pre;
            pre = cur;
            cur = Next;
        }
        return pre;
    }
    ListNode* reverseBetween(ListNode* head, int left, int right)
    {
        ListNode* dummyNode, * pre;
        dummyNode = pre = new ListNode(-1);
        dummyNode->next = head;
        for (int i = 0; i < left - 1; ++i)
        {
            pre = pre->next;
        }
        ListNode* leftNode = pre->next;
        ListNode* rightNode = pre;
        for (int i = 0; i < right - left + 1; ++i)
        {
            rightNode = rightNode->next;
        }
        ListNode* Next = rightNode->next;
        pre->next = rightNode->next = nullptr;
        pre->next = reverse(leftNode);
        leftNode->next = Next;
        head = dummyNode->next;
        delete dummyNode;
        return head;
    }
};

